# -*- coding: utf-8 -*-
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from itsdangerous import TimedJSONWebSignatureSerializer as Serilazer


from lab import settings
from user.models import User

serilazer = Serilazer(settings.SECRET_KEY, 3600 * 24)


class MyAuthentication(BaseAuthentication):
    '''身份认证'''

    def authenticate(self, request):
        token = request.META.get("HTTP_AUTHORIZATION", "")
        if token == "":
            token = request.META.get("HTTP_TOKEN", "")
        if token == "":
            raise AuthenticationFailed
        decode_token = serilazer.loads(token)
        try:
            username = decode_token.get('username')
            user = User.objects.filter(username=username)
            if len(user) == 0:
                    raise AuthenticationFailed
        except Exception:
            raise AuthenticationFailed
        return user.first(), token


# class DeviceAuthentication(BaseAuthentication):
#     '''设备token认证'''
#
#     def authenticate(self, request):
#         try:
#             token = request.META.get("HTTP_AUTHORIZATION", "")
#             if token == "":
#                 token = request.META.get("HTTP_TOKEN", "")
#             if token == "":
#                 raise AuthenticationFailed
#             print(token)
#             payload = jwt.decode(token, SECRET_KEY, audience='platform-user', algorithms=['HS256'])
#             print(payload)
#             device_obj = Device.objects.filter(id=payload.get("device_id")).first()
#             print(device_obj.id)
#             exp = payload.get("exp", "")
#             if payload:
#                 if exp != "":
#                     if exp - int(time.time()) < 0:
#                         raise AuthenticationFailed
#                 request.META.update(**payload)
#                 return device_obj.sub_user, payload
#             else:
#                 raise AuthenticationFailed
#         except Exception as e:
#             print(str(e))
#             raise AuthenticationFailed
